#!/usr/bin/python
# -*- coding: utf-8 -*-
import os

import shutil
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QStandardItemModel, QStandardItem, QMessageBox

from util.logger import process_log

__author__ = 'xiwei'


class TabMap:
    def __init__(self):
        pass

    ORIGIN = 0
    MD5 = 1
    LOCAL = 2
    ALIYUN = 3
    LOG = 4


class AppStatus:
    def __init__(self):
        pass

    UPGRADING = 1
    SYNCING = 2


class MessageBox:
    Ok = QMessageBox.Ok
    Yes = QMessageBox.Yes

    No = QMessageBox.No
    Cancel = QMessageBox.Cancel

    def __init__(self, parent=None, style=QMessageBox.Information, title=u'提示', info='', btn=QMessageBox.Cancel):
        if parent:
            self.box = QMessageBox(style, title, info, btn, parent)

    def show(self):
        self.box.show()

    def text(self, text):
        self.box.setText(u'%s' % text)
        self.show()

    def hidden(self):
        self.box.hide()

    @staticmethod
    def create_box(style, title, info, btn):
        box = QMessageBox(style, title, u'%s' % info)
        box.setStandardButtons(btn)
        box.setButtonText(QMessageBox.Yes, u'确定')
        box.setButtonText(QMessageBox.Ok, u'确定')
        box.setButtonText(QMessageBox.No, u'取消')
        box.setButtonText(QMessageBox.Cancel, u'取消')
        return box.exec_()

    def information(self, parent, title, info, btn=QMessageBox.Yes):
        return self.create_box(QMessageBox.Information, title, info, btn)

    def critical(self, parent, title, info, btn=QMessageBox.Yes):
        return self.create_box(QMessageBox.Critical, title, info, btn)


def create_field_list_model(fields):
    model = QStandardItemModel()
    model_name = []
    model_type = []
    for field in fields:
        fd_item_name = QStandardItem(field['name'])
        fd_item_name.setToolTip(field['name'])
        fd_item_type = QStandardItem(field['type'])
        fd_item_name.setCheckable(True)
        if field['selected'] == 1:
            fd_item_name.setCheckState(Qt.Checked)
        else:
            fd_item_name.setCheckState(Qt.Unchecked)
        model_name.append(fd_item_name)
        model_type.append(fd_item_type)
    model.appendColumn(model_name)
    model.appendColumn(model_type)
    return model


def clicked_item(index):
    """
        Find the database and table that user clicked
    Args:
        index: QStanderItemIndex
    Returns:
        (
            db_item: QStandardItem,
            tb_item: QStandardItem
        )
    """
    item_clicked = index.model().itemFromIndex(index)

    parent = item_clicked.parent()

    if parent:
        db_item = parent
        tb_item = item_clicked
    else:
        db_item = item_clicked
        tb_item = None

    return db_item, tb_item


def set_table_state(model, message):
    """
        Set the table state which display in the sync tab table treeview.
    Args:
        model: the sync table treeview data model
        message: message which receive from message loop
    """
    database = message.get('database')
    table = message.get('table')
    state = message.get('state')

    for index in range(0, model.rowCount()):
        db_item = model.item(index)
        if db_item.text() == database:
            for i in range(0, db_item.rowCount()):
                tb_item = db_item.child(i)

                if tb_item.text() == table:
                    tb_item.setBackground(state)
                    break


def render_sync_tree(model, dbs):
    model.removeRows(0, model.rowCount())
    for db in dbs:

        db_name = db.get('database')
        if not db_name:
            return
        db_model = QStandardItem(db_name)

        for tb in db.get('append_table'):
            tb_name = tb.get('name')
            tb_model = QStandardItem(tb_name)
            db_model.appendRow(tb_model)

        model.appendRow(db_model)


def render_database_tree(tree_view_model, data):
    if not tree_view_model:
        return
    tree_view_model.removeRows(0, tree_view_model.rowCount())
    for db in sorted(data.keys()):
        db_item = QStandardItem(db)
        db_item.setToolTip(db)
        db_item.setCheckable(True)
        count = len(data.get(db))
        for tb in sorted(data.get(db).keys()):
            selected = data.get(db).get(tb).get('selected', 0)
            tb_item = QStandardItem(tb)
            tb_item.setToolTip(tb)
            tb_item.setCheckable(True)
            if selected == 1:
                count -= 1
                tb_item.setCheckState(Qt.Checked)
                data[db][tb]['model'] = create_field_list_model(data[db][tb]['fields'])
            db_item.appendRow(tb_item)
        if count == 0 and len(data.get(db)) != 0:
            db_item.setCheckState(Qt.Checked)
        elif count == len(data.get(db)):
            pass
        else:
            db_item.setCheckState(Qt.PartiallyChecked)
        if len(data.get(db)) == 0:
            db_item.setEnabled(False)
        tree_view_model.appendRow(db_item)


def copy_and_overwrite(src, dst):
    for src_dir, dirs, files in os.walk(src):
        dst_dir = src_dir.replace(src, dst, 1)
        if not os.path.exists(dst_dir):
            os.mkdir(dst_dir)
        for file_ in files:
            if file_ == 'logging.conf':
                continue
            src_file = os.path.join(src_dir, file_)
            dst_file = os.path.join(dst_dir, file_)
            if os.path.exists(dst_file):
                os.remove(dst_file)
            process_log().info("Recover data from [%s] to [%s]" % (src_file, dst_file))
            shutil.move(src_file, dst_dir)

